﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ReservaCancha.Models;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using System.Text;

namespace ReservaCancha.Controllers
{
    public class Reserva1Controller : Controller
    {
        private List<Reserva1> CrearReservas()
        {

            /*HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:5158/Reservas.svc/Reservas");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string recursoJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<Reserva1> reservas = js.Deserialize<List<Reserva1>>(recursoJson);
            return reservas;*/
            /*Cancha cancha1 = new Cancha() { Codigo = 1, Nombre = "Pizarro" };
            Cancha cancha2 = new Cancha() { Codigo = 2, Nombre = "Farfan" };
            Cancha cancha3 = new Cancha() { Codigo = 3, Nombre = "Guerrero" };
            Cancha cancha4 = new Cancha() { Codigo = 4, Nombre = "Vargas" };

            Cliente cliente1 = new Cliente() { Codigo = 1, Nombre = "Wilfredo Champi" };
            Cliente cliente2 = new Cliente() { Codigo = 1, Nombre = "Joel Rodriguez" };
            Cliente cliente3 = new Cliente() { Codigo = 1, Nombre = "Liliana Espinoza" };
            Cliente cliente4 = new Cliente() { Codigo = 1, Nombre = "Miguel Valer" };

            Reserva1 reserva1 = new Reserva1() { Codigo = 1, Cancha = cancha1, Dia = "Lunes", Hora = "8:00 - 9:00", Estado = "Disponible", Cliente = cliente1 };
            Reserva1 reserva2 = new Reserva1() { Codigo = 2, Cancha = cancha1, Dia = "Martes", Hora = "8:00 - 9:00", Estado = "Disponible", Cliente = cliente1 };
            Reserva1 reserva3 = new Reserva1() { Codigo = 3, Cancha = cancha1, Dia = "Miércoles", Hora = "8:00 - 9:00", Estado = "Disponible", Cliente = cliente2 };
            Reserva1 reserva4 = new Reserva1() { Codigo = 4, Cancha = cancha1, Dia = "Jueves", Hora = "8:00 - 9:00", Estado = "Disponible", Cliente = cliente3 };
            Reserva1 reserva5 = new Reserva1() { Codigo = 5, Cancha = cancha1, Dia = "Viernes", Hora = "8:00 - 9:00", Estado = "Disponible", Cliente = cliente1 };
            Reserva1 reserva6 = new Reserva1() { Codigo = 6, Cancha = cancha1, Dia = "Sábado", Hora = "8:00 - 9:00", Estado = "Disponible", Cliente = cliente3 };
            Reserva1 reserva7 = new Reserva1() { Codigo = 7, Cancha = cancha1, Dia = "Domingo", Hora = "8:00 - 9:00", Estado = "Disponible", Cliente = cliente1 };
            List<Reserva1> reservas = new List<Reserva1>();
            reservas.Add(reserva1);
            reservas.Add(reserva2);
            reservas.Add(reserva3);
            reservas.Add(reserva4);
            reservas.Add(reserva5);
            reservas.Add(reserva6);
            reservas.Add(reserva7);
            return reservas;*/

            HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:3634/Reservas.svc/Reservas");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string reservaJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<Reserva1> reservas = js.Deserialize<List<Reserva1>>(reservaJson);
            return reservas;

        }

        private Reserva1 ObtenerReserva(int codigo)
        {

            string codigo1 = Convert.ToString(codigo);
            HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:5158/Reservas.svc/Reservas/" + codigo1);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string reservaJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<Reserva1> reservas = js.Deserialize<List<Reserva1>>(reservaJson);
            Reserva1 model = js.Deserialize<Reserva1>(reservaJson);
            return model;

        }


        //
        // GET: /Reserva/

        public ActionResult Index()
        {
            /*if (Session["reservas"] == null)
                Session["reservas"] = CrearReservas();

            HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:5158/Reservas.svc/Reservas");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string reservaJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<Reserva1> model = js.Deserialize<List<Reserva1>>(reservaJson);
            return View(model);*/

            /*if (Session["reservas"] == null)
                Session["reservas"] = CrearReservas();
            List<Reserva1> model = (List<Reserva1>)Session["reservas"];
            return View(model);*/

            if (Session["reservas"] == null)
                Session["reservas"] = CrearReservas();

            HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:3634/Reservas.svc/Reservas");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string reservaJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<Reserva1> model = js.Deserialize<List<Reserva1>>(reservaJson);
            return View(model);
        }

        //
        // GET: /Reserva/Details/5

        public ActionResult Details(int id)
        {
            //return View();
            Reserva1 model = ObtenerReserva(id);
            return View(model);
        }

        //
        // GET: /Reserva/Create

        public ActionResult Create()
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:3634/Clientes.svc/Clientes");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string clienteJson = reader.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<Cliente> clientes = js.Deserialize<List<Cliente>>(clienteJson);
            var list = new SelectList(clientes, "Codigo", "Nombre");
            ViewData["clientes"] = list;

            HttpWebRequest req1 = (HttpWebRequest)WebRequest
                .Create("http://localhost:3634/Canchas.svc/Canchas");
            req1.Method = "GET";
            HttpWebResponse res1 = (HttpWebResponse)req1.GetResponse();
            StreamReader reader1 = new StreamReader(res1.GetResponseStream());
            string canchaJson = reader1.ReadToEnd();
            JavaScriptSerializer js1 = new JavaScriptSerializer();
            List<Cancha> canchas = js1.Deserialize<List<Cancha>>(canchaJson);
            var list1 = new SelectList(canchas, "Codigo", "Nombre");
            ViewData["canchas"] = list1;

            HttpWebRequest req2 = (HttpWebRequest)WebRequest
                .Create("http://localhost:3634/Horas.svc/Horas");
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string horainiJson = reader2.ReadToEnd();
            JavaScriptSerializer js2 = new JavaScriptSerializer();
            List<Horario> horaini = js2.Deserialize<List<Horario>>(horainiJson);
            var list2 = new SelectList(horaini, "Codigo", "Nombre");
            ViewData["horaini"] = list2;

            HttpWebRequest req3 = (HttpWebRequest)WebRequest
                .Create("http://localhost:3634/Horas.svc/Horas");
            req3.Method = "GET";
            HttpWebResponse res3 = (HttpWebResponse)req3.GetResponse();
            StreamReader reader3 = new StreamReader(res3.GetResponseStream());
            string horafinJson = reader3.ReadToEnd();
            JavaScriptSerializer js3 = new JavaScriptSerializer();
            List<Horario> horafin = js3.Deserialize<List<Horario>>(horafinJson);
            var list3 = new SelectList(horafin, "Codigo", "Nombre");
            ViewData["horafin"] = list3;

            return View();

        }

        //
        // POST: /Reserva/Create

        //[HttpPost]
        //public ActionResult Create(FormCollection collection)
        //{
        //    try
        //    {
        //        // TODO: Add insert logic here

        //        return RedirectToAction("Index");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                string postdata = "{\"Codigo\":\"" + collection["Codigo"] + "\",\"Cliente\":\"" + collection["clientes"] + "\",\"Cancha\":\"" + collection["canchas"] + "\" ,\"Fecha\":\"" + collection["txtFechaInicioEmision"] + "\",\"Inicio\":\"" + collection["horaini"] + "\",\"Fin\":\"" + collection["horafin"] + "\",\"Monto\":\"" + collection["Monto"] + "\" }";
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest
                    .Create("http://localhost:3634/Reservas.svc/Reservas");
                req.Method = "POST";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                HttpWebResponse res = null;
                res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string reservaJson = reader.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                Reserva1 recursoCreado = js.Deserialize<Reserva1>(reservaJson);
                return RedirectToAction("Index");

            }
            catch (WebException e)
            { 
              HttpWebResponse resError = (HttpWebResponse)e.Response;
                    StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                    string error = reader2.ReadToEnd();
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    string errorMessage = js.Deserialize<string>(error);
                    TempData["mensaje"] = errorMessage;
                    return RedirectToAction("Create");
            
            }

            return RedirectToAction("Index");
        }
            



        //
        // GET: /Reserva/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                Reserva1 model = ObtenerReserva(id);
                string postdata1 = "{\"Codigo\":\"" + collection["Codigo"] + "\",\"Fecha\":\"" + collection["fecha"] + "\",\"Hora Inicio\":\"" + collection["inicio"] + "\",\"Hora Fin\":\"" + collection["fin"] + "\",\"Cancha\":\"" + collection["canchas"] + "\",\"Cliente\":\"" + collection["clientes"] + "\",\"Monto\":\"" + collection["monto"] + "\",\"Estado\":\"" + collection["estado"] + "\" }";
                byte[] data1 = Encoding.UTF8.GetBytes(postdata1);
                HttpWebRequest req3 = (HttpWebRequest)WebRequest
                    .Create("http://localhost:5158/Reservas.svc/Reservas");
                req3.Method = "PUT";
                req3.ContentLength = data1.Length;
                req3.ContentType = "application/json";
                var reqStream1 = req3.GetRequestStream();
                reqStream1.Write(data1, 0, data1.Length);
                var res3 = (HttpWebResponse)req3.GetResponse();
                StreamReader reader3 = new StreamReader(res3.GetResponseStream());
                string reservaJson3 = reader3.ReadToEnd();
                JavaScriptSerializer js3 = new JavaScriptSerializer();
                Reserva1 reservaModificado = js3.Deserialize<Reserva1>(reservaJson3);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // POST: /Reserva/Valid/5

        [HttpPost]
        public ActionResult Valid(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Reserva/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Reserva/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                string postdata2 = "{\"Codigo\":\"" + collection["Codigo"] + "\"}";
                byte[] data2 = Encoding.UTF8.GetBytes(postdata2);
                HttpWebRequest req4 = (HttpWebRequest)WebRequest
                    .Create("http://localhost:5158/Reservas.svc/Reserva/" + id);
                req4.Method = "DELETE";
                req4.ContentLength = data2.Length;
                req4.ContentType = "application/json";
                var reqStream2 = req4.GetRequestStream();
                reqStream2.Write(data2, 0, data2.Length);
                var res4 = (HttpWebResponse)req4.GetResponse();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}